package dinosaur;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Timer;

/**
 * @author Grey
 * 间隔一定的时间设置速度（匀加速）
 * 记录玩家得分，其中包括最高得分以及当前游戏结束得分
 */

public class ScoreThread extends Thread implements Comparator<String> {

    private Timer timer;
    private double score = 0;
    private ArrayList<String> tempRank;
    private boolean initHighest = false;
    private Date date;
    private final int BOARD_WIDTH = 750;
    private final int BOARD_HEIGHT = 850;

    ScoreBoard scoreBoard = new ScoreBoard();
    File file = new File(new File("score.txt").getAbsolutePath());

    ScoreThread() {
        //scoreBoard.setLayout(null);
        scoreBoard.setLocation(680, 136); //确定显示位置
        scoreBoard.setSize(BOARD_WIDTH, BOARD_HEIGHT); //设置窗口大小
        scoreBoard.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        timer = new Timer();
    }

    @Override
    public void run() {
        if (DinosaurMain.state == DinosaurMain.PLAYING) {
            speedUp();
            try {
                scoreRecord();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void speedUp() {
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (DinosaurMain.state == DinosaurMain.PLAYING) {
                    DinosaurMain.setSpeed((DinosaurMain.speed + 1));
                    DinosaurThread.setMillis(DinosaurThread.getMillis() - (long) 0.5);
                    System.out.println("+++++  Speed up... +++++");
                    System.out.println("> Now speed: " + DinosaurMain.speed);
                }
            }
        }, 7000, 13000);//7s之后，每13s增速一次，增速幅度为1
    }

    public void cancleTimer() {
        this.timer.cancel();
    }

    public void setScore(double score) {
        this.score = score;
    }

    public double getScore() {
        score += ((double) DinosaurMain.speed / 10000) * 100;
        return score;
    }

    public double getHighScore() {
        if (score > scoreBoard.getHighestScore())
            scoreBoard.setHighestScore(score);
        return scoreBoard.getHighestScore();
    }

    public void scoreRecord() throws IOException {
        double maxRank = 0;
        if (scoreBoard.createFile(file)) {
            System.out.println("Create File successfully!");
        }
        tempRank = (ArrayList) scoreBoard.readFile(file);
        if (tempRank.isEmpty()) {
            maxRank = 0;
        } else {
            maxRank = Double.parseDouble(subToString(tempRank.get(0)));
        }
        if (!initHighest) {
//            初始化最高分
            System.out.println("init maxRank:" + maxRank);
            scoreBoard.setHighestScore(maxRank);
            initHighest = true;
        }
    }

    @Override
    public int compare(String o1, String o2) {
        double d1 = Double.parseDouble(subToString(o1));
        double d2 = Double.parseDouble(subToString(o2));
        if (d1 < d2)
            return 1;
        else if (d1 > d2)
            return -1;
        else
            return 0;
    }

    public void recordRank() throws IOException {
        date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("MM.dd HH:mm:ss");
        tempRank.add("Score:" + String.format("%.0f", score) + " | " + "Time:" + sf.format(date));
        Collections.sort(tempRank, this::compare);
        try {
            new FileWriter(file, false);
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (String si : tempRank) {
            scoreBoard.writeFile(file, si);
        }
        System.out.println("write File successfully!");
    }

    //    分割字符串
    public String subToString(String str) {
        String substr = str.substring(str.indexOf("Score:") + 6, str.indexOf(" | "));
        return substr;
    }

    private JLabel lab = new JLabel();
    private JTextArea scoreArea = new JTextArea();
    private JScrollPane jsp = new JScrollPane(scoreArea);
    private JPanel panel = new JPanel();

    public void updateScore() {
        try {
            scoreRecord();
        } catch (IOException e) {
            e.printStackTrace();
        }
        scoreArea.setText("");
        jsp.setBounds(5, 5, BOARD_WIDTH, BOARD_HEIGHT - 20);
        panel.add(lab);
        //panel.add(scoreArea);
        panel.add(jsp);
        panel.setLayout(new FlowLayout(FlowLayout.CENTER));
        scoreArea.setEditable(false);
        scoreArea.setFont(new Font("Consolas", Font.PLAIN, 25));
        scoreArea.setBounds(5, 5, 300, 500);
        scoreArea.setTabSize(2);
        scoreArea.setBackground(new Color(238, 238, 238));
        scoreArea.append("\n\n");
        int num = 1;
        for (String s :
                tempRank) {
            int score = Integer.parseInt(s.substring(s.indexOf("Score:") + 6, s.indexOf(" ")));
            String date = s.substring(s.indexOf("Time:") + 5);
            scoreArea.append(String.format("   [%02d]\t\t", num));
            scoreArea.append(String.format("Score: %6d | Date: %s   \n\n",score,date));

            if (++num > 10)
                break;
        }
        lab.setText("排 行 榜");
        lab.setFont(new Font("Microsoft Yahei", Font.PLAIN, 40));
        lab.setLocation(100, 10);
        scoreBoard.setResizable(false);
        scoreBoard.setTitle("排行榜");
        scoreBoard.add(panel);
    }

    public void showScoreBoard() {
        updateScore();
        scoreBoard.setVisible(true);
    }

    public ScoreBoard getScoreBoard() {
        return scoreBoard;
    }
}
